import java.util.Arrays;

/**
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
 */
public class Solutions_34 {
    public static void main(String[] args) {
//        int[] nums = {5, 7, 7, 8, 8, 10};
//        int target = 8;  // output: {3, 4}

//        int[] nums = {5, 7, 7, 8, 8, 10};
//        int target = 6;  // output: {-1, -1}

        int[] nums = {};
        int target = 0;  // output: {-1, -1}

        int[] result = searchRange(nums, target);
        System.out.println(Arrays.toString(result));
    }

    /**
     * 解题思路：
     * 1. 在升序数组中进行二分查找，查找到 target 所在的索引（如果有）
     * 2. 查找到 target 后，以 mid 为中心，向左右两侧扩展
     */
    public static int[] searchRange(int[] nums, int target) {
        int[] res = {-1, -1};
        if (nums == null || nums.length < 1) {
            return res;
        }
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                // 找到 target
                int start = mid, end = mid;
                // 向左扩展
                while (start > 0 && nums[start - 1] == target) {
                    start --;
                }
                // 向右扩展
                while (end < nums.length - 1 && nums[end + 1] == target) {
                    end ++;
                }
                res[0] = start;
                res[1] = end;
                break;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return res;
    }
}
